using DesktopApp.ViewModels; // For RuleItemViewModel, RuleStats
using System;
using System.Collections.Generic;
using System.Linq;

namespace DesktopApp.ViewModels.Services
{
    public class StatisticsService : IStatisticsService
    {
        private static readonly string[] _lineSeparators = { "\r\n", "\r", "\n" };

        public int CalculateLineCount(string? text)
        {
            if (string.IsNullOrEmpty(text))
            {
                return 0;
            }
            // Split and count. Add 1 because Split removes the last empty element if the string ends with a newline.
            // However, a single line without a newline should be count 1. Let's simplify:
            return text.Split(_lineSeparators, StringSplitOptions.None).Length;
        }

        public double? CalculateReductionPercentage(int originalCount, int resultCount)
        {
            if (originalCount <= 0)
            {
                return null; // Avoid division by zero and meaningless percentage
            }
            // Ensure result count isn't negative (though unlikely)
            resultCount = Math.Max(0, resultCount); 
            return 100.0 * (originalCount - resultCount) / originalCount;
        }

        public RuleStats CalculateRuleStats(IEnumerable<RuleItemViewModel> rules)
        {
            if (rules == null)
            {
                return new RuleStats(0, 0);
            }
            // Use caching ToList() if the enumeration might be expensive or used multiple times.
            var rulesList = rules.ToList(); 
            int enabledCount = rulesList.Count(r => r.IsEnabled);
            int totalCount = rulesList.Count;
            return new RuleStats(enabledCount, totalCount);
        }

        public string GenerateAppliedRulesSummary(IEnumerable<RuleItemViewModel> rules)
        {
            if (rules == null)
            {
                 return "已应用: 无";
            }

            var enabledRuleNames = rules.Where(r => r.IsEnabled).Select(r => r.Name).ToList();
            
            if (enabledRuleNames.Any())
            {
                // Consider truncating if the list is very long
                const int maxRulesToShow = 5;
                string summary = string.Join(", ", enabledRuleNames.Take(maxRulesToShow));
                if (enabledRuleNames.Count > maxRulesToShow)
                {
                    summary += $", ...等{enabledRuleNames.Count}项";
                }
                return $"已应用: {summary}";
            }
            else
            {
                return "已应用: 无";
            }
        }
    }
} 